package edu.sysu.demo.petstore.dog.web.rest;

import edu.sysu.demo.petstore.dog.issue.IssueTokenService;
import edu.sysu.demo.petstore.dog.user.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lijinting01
 */
@RestController
@RequestMapping("/account/login")
public class LoginController {

  private final LoginService loginService;

  private final IssueTokenService issueTokenService;

  @Autowired
  public LoginController(LoginService loginService,
      IssueTokenService issueTokenService) {
    this.loginService = loginService;
    this.issueTokenService = issueTokenService;
  }

  @PostMapping
  public String login(@RequestBody LoginForm loginForm) {
    String subject = loginForm.getUsername();
    if (loginService.login(subject, loginForm.getPassword())) {
      return issueTokenService.issue(subject);
    }

    throw new BadCredentialsException(subject);
  }

}

